#include "Mylogger.hh"
#include "servicecode/SplitTool.h"
#include "servicecode/MyTask.h"
#include "servicecode/HttpRequest.h"
#include "servicecode/HttpResponse.h"
#include "servicecode/WebPageSearch.h"
#include "servicecode/LoadWebPage.h"
#include "Dictionary/KeyRecommander.h"
#include "PagePreprocess/WebPage.h"

MyTask::MyTask(const HttpRequest &httpreq, const TcpConnectionPtr &con)
    : _httpreq(httpreq), _con(con)
{
}

void MyTask::process()
{
    // 解析http请求
    HttpParser(_httpreq);
}

// 解析http请求
void MyTask::HttpParser(HttpRequest &http)
{
    string buf = http._path; // /path?key=value
    string path = buf.substr(0, buf.find("?"));
    string key = buf.substr(buf.find("?") + 1, buf.find("=") - 1);
    string value = buf.substr(buf.find("=") + 1);
    if (http._method == "GET")
    {
        if (path == "/") // post主页面
        {
            HttpResponse http_rsp;
            http_rsp.set_html_body("data/html/SearchEngine_v2.html");
            _con->sendInLoop(http_rsp.get_html_response());
        }
        else if (path == "/suggest") // 关键词推荐
        {
            KeyRecommand(value);
        }
        else if (path == "/search") // 网页搜索
        {
            WebPageRecommand(value);
        }
    }
}

// 关键词推荐
void MyTask::KeyRecommand(const string &sought)
{
    KeyRecommander candidate(sought); // 关键词查询
    string can = candidate.priority_queue_pop(10);//获得查询结果
    LogDebug("返回推荐词:%s", can.c_str());
    // 生成响应
    HttpResponse http_rsp;
    http_rsp.set_str_body(can);
    _con->sendInLoop(http_rsp.get_html_response());
}

//相关网页推荐
void MyTask::WebPageRecommand(const string &value)
{
    WebPageSearch wps(value);
    if (!wps.toSearch())
    {
        LogInfo("未搜到相关网页");
        return;
    }
   
    string & json_string = wps.getresult(); // 获得搜索结果
   
    LogInfo("生成http响应");
    HttpResponse http_rsp;
    http_rsp.set_str_body(json_string);
    _con->sendInLoop(http_rsp.get_html_response());
}